﻿using MediatR;
using Production_Get.API.DTO;
using Production_Get.API.Infrastructures.Interfaces;
using Return.Enum;
using THE_WIND_RISES.Common.Domans.Produce.Customers;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Get.API.Application.Commands.CustomerShow
{
    /// <summary>
    /// 客户列表
    /// </summary>
    public class CustomerSrcetenHandler : IRequestHandler<CustomerSrcetenCommend, Result>
    {
        private readonly IBaseRepositoryGet<CustomerDto> CustomerDto;

        public CustomerSrcetenHandler(IBaseRepositoryGet<CustomerDto> CustomerDto)
        {
            this.CustomerDto = CustomerDto;
        }

        public async Task<Result> Handle(CustomerSrcetenCommend request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCodes.Search };

            string sql = "SELECT * FROM Customer a INNER JOIN Industry b on a.IndustryId=b.IndustryId where a.IsDelete=0";
            CustomerDto come = new CustomerDto();
            var list = CustomerDto.GetAll(sql, come).ToList();

            if (!string.IsNullOrEmpty(request.CustomerNo))
            {
                list = list.Where(x => x.CustomerNo.Contains(request.CustomerNo)).ToList();
            }

            if (!string.IsNullOrEmpty(request.CustomerName))
            {
                list = list.Where(x => x.CustomerName.Contains(request.CustomerName)).ToList();
            }

            if (!string.IsNullOrEmpty(request.CityId))
            {
                list = list.Where(x => x.CityId == request.CityId).ToList();
            }

            if (!string.IsNullOrEmpty(request.CustomerType))
            {
                list = list.Where(x => x.CustomerType == request.CustomerType).ToList();
            }

            if (request.CustomerState != null)
            {
                list = list.Where(x => x.CustomerState == request.CustomerState).ToList();
            }

            var totalcount = list.Count();
            var pagecount = (int)Math.Ceiling(totalcount * 1.0 / request.pageSize);
            list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            var lief = new
            {
                totalcount,
                pagecount,
                list,
            };

            if (list != null)
            {
                result.Code = (int)CommonErrorCodes.Success;
                result.Data = lief;
                result.Msg = "显示成功";
            }
            else
            {
                result.Msg = "显示失败";
            }
            return result;
        }
    }
}
